const express = require('express');
const cors = require('cors');
const bodyParser = require('body-parser');
const dotenv = require('dotenv');
const { testConnection, syncDatabase } = require('./config/database');

// 加载环境变量
dotenv.config();

// 加载模型关联关系（必须在路由之前）
require('./models/index');

const app = express();

// 中间件
app.use(cors());
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));

// 连接并初始化数据库
const initDatabase = async () => {
  try {
    // 测试连接
    const isConnected = await testConnection();
    
    if (isConnected) {
      // 同步数据库表（开发环境可设置 force: true 重建表）
      await syncDatabase(false);
    } else {
      console.error('⚠️  数据库连接失败，请检查配置');
      process.exit(1);
    }
  } catch (error) {
    console.error('❌ 数据库初始化失败:', error.message);
    process.exit(1);
  }
};

// 初始化数据库
initDatabase();

// 导入路由
const authRoutes = require('./routes/auth');
const categoryRoutes = require('./routes/category');
const fruitRoutes = require('./routes/fruit');
const warehouseRoutes = require('./routes/warehouse');
const statsRoutes = require('./routes/stats');

// 使用路由
app.use('/api/auth', authRoutes);
app.use('/api/categories', categoryRoutes);
app.use('/api/fruits', fruitRoutes);
app.use('/api/warehouses', warehouseRoutes);
app.use('/api/stats', statsRoutes);

// 基础路由
app.get('/', (req, res) => {
  res.json({ 
    message: 'Fruit Management System API',
    version: '1.0.0',
    database: 'MySQL',
    endpoints: {
      auth: {
        login: 'POST /api/auth/login',
        profile: 'GET /api/auth/profile (Authentication required)'
      },
      fruits: {
        list: 'GET /api/fruits',
        detail: 'GET /api/fruits/:id',
        create: 'POST /api/fruits',
        update: 'PUT /api/fruits/:id',
        delete: 'DELETE /api/fruits/:id',
        batchDelete: 'POST /api/fruits/batch-delete'
      },
      warehouses: {
        list: 'GET /api/warehouses',
        detail: 'GET /api/warehouses/:id',
        create: 'POST /api/warehouses',
        update: 'PUT /api/warehouses/:id',
        delete: 'DELETE /api/warehouses/:id',
        batchDelete: 'POST /api/warehouses/batch-delete',
        fruits: {
          list: 'GET /api/warehouses/:id/fruits',
          add: 'POST /api/warehouses/:id/fruits',
          update: 'PUT /api/warehouses/:id/fruits/:fruitWarehouseId',
          remove: 'DELETE /api/warehouses/:id/fruits/:fruitWarehouseId'
        }
      },
      stats: {
        get: 'GET /api/stats (Authentication required)'
      }
    }
  });
});

// 错误处理中间件
app.use((err, req, res, next) => {
  console.error('错误堆栈:', err.stack);
  
  // Sequelize 验证错误
  if (err.name === 'SequelizeValidationError') {
    return res.status(400).json({
      success: false,
      message: err.errors[0].message || '数据验证失败'
    });
  }
  
  // Sequelize 唯一约束错误
  if (err.name === 'SequelizeUniqueConstraintError') {
    const field = err.errors[0].path;
    let message = '该数据已存在';
    if (field === 'username') {
      message = '用户名已被使用';
    } else if (field === 'email') {
      message = '邮箱已被注册';
    }
    return res.status(400).json({
      success: false,
      message
    });
  }
  
  res.status(500).json({ 
    success: false,
    message: '服务器内部错误',
    error: process.env.NODE_ENV === 'development' ? err.message : undefined
  });
});

// 404 处理
app.use((req, res) => {
  res.status(404).json({ 
    success: false,
    message: '请求的资源不存在' 
  });
});

// 启动服务器
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
  console.log(`🚀 服务器运行在端口 ${PORT}`);
  console.log(`📍 访问 http://localhost:${PORT}`);
});

module.exports = app;
